package com.bbva.log4j.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import com.bbva.common.listener.SpringInit.SpringInit;
import com.bbva.persistencia.generica.dao.GenericDao;
import com.bbva.persistencia.generica.modelo.Log4jdata;
import com.bbva.persistencia.generica.util.Busqueda;
import com.bbva.persistencia.generica.util.Utilitarios;

@ManagedBean(name = "log4MB")
@SessionScoped
public class Log4jManager  implements Serializable {

	private static Logger log = Logger.getLogger(Log4jManager.class);
	private static final long serialVersionUID = 1L;

	private List<Log4jdata> lstLogger = null;
	private List<SelectItem> lstLevel;
	private LoggerFiltroDTO slogfilter;
	private Integer iCantLogger;
	private StreamedContent file;
	private String sPath; // C:/resources/logConsola.txt
	private String sValuePaquete;

	public Log4jManager() {
		log.info("Estoy en el constructor de Log4jManager");
		lstLogger = new ArrayList<Log4jdata>();
		comboboxLevel();
		slogfilter = new LoggerFiltroDTO();

	}

	public void comboboxLevel() {

		lstLevel = new ArrayList<SelectItem>();
		lstLevel.add(new SelectItem(Utilitarios.TRACE, "TRACE"));
		lstLevel.add(new SelectItem(Utilitarios.DEBUG, "DEBUG"));
		lstLevel.add(new SelectItem(Utilitarios.INFO, "INFO"));
		lstLevel.add(new SelectItem(Utilitarios.WARN, "WARN"));
		lstLevel.add(new SelectItem(Utilitarios.ERROR, "ERROR"));
		lstLevel.add(new SelectItem(Utilitarios.FATAL, "FATAL"));

	}

	public void filtrarLogger() {

		Utilitarios.putObjectInSession("lstLogger", new ArrayList<Log4jdata>());
		try {

			GenericDao<Log4jdata, LoggerFiltroDTO> entidadDAO = (GenericDao<Log4jdata, LoggerFiltroDTO>) SpringInit.getApplicationContext().getBean("genericoDao");
			if (entidadDAO != null) {

				Busqueda filtro = Busqueda.forClass(Log4jdata.class);
				filtro.addOrder(Order.asc("id")).add(Expression.like("thead","%" + slogfilter.getsThread() + "%"))
						                        .add(Expression.like("mensaje","%" + slogfilter.getsLogger() + "%"))
						                        .add(Expression.like("clase","%" + slogfilter.getsMessage() + "%"))
						                        .add(Expression.like("prioridad",slogfilter.getsLevel() + "%"));

				if (slogfilter.getsFInicio() != null) {
					filtro.add(Expression.ge("fecha", slogfilter.getsFInicio()));
				}
				if (slogfilter.getsFFin() != null) {
					filtro.add(Expression.le("fecha", slogfilter.getsFFin()));
				}

				int i = 0;
				lstLogger = entidadDAO.buscarDinamico(filtro);
				for (Log4jdata log : lstLogger) {
					i++;
					log.setItem(i);
				}
				iCantLogger = lstLogger.size();
				System.out.println("iCantLogger : " + iCantLogger);
				// Poner la lista del Reporte en Session
				Utilitarios.putObjectInSession("lstLogger", lstLogger);
			}// Fin del If
			else {
				log.info("El objeto es Nullo .... ");

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void limpiar() {
		log.info("En el metodo limpiar()");
		slogfilter = new LoggerFiltroDTO();
		iCantLogger = 0;
	}

	public void dowloadLogger() {
		log.info("dowloadLogger   ");

		try {
			if (sPath != null && sPath != "") {
				File fl = new File(sPath);

				if (fl.exists()) {
					InputStream stream = new FileInputStream(fl);
					log.info("si existe");
					file = new DefaultStreamedContent(stream,"application/txt", "downloaded_file.txt");
				}
			} else {
				Utilitarios.mensajeInfo("Info :","Ingrese la ruta a descargar.");
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void grabarNivelPaquete() {
		try {
            if(sValuePaquete!=""){
            	cambioNivelLogger(sValuePaquete);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	private void cambioNivelLogger(String logLevel) {
		log.info("en el cambioNivelLogger " + logLevel);
		Logger root = Logger.getRootLogger();
		boolean exiteNivelLogger = true;
		if ("TRACE".equalsIgnoreCase(logLevel)) {
			root.setLevel(Level.TRACE);
		} else if ("DEBUG".equalsIgnoreCase(logLevel)) {
			root.setLevel(Level.DEBUG);
		} else if ("INFO".equalsIgnoreCase(logLevel)) {
			root.setLevel(Level.INFO);
		} else if ("WARN".equalsIgnoreCase(logLevel)) {
			root.setLevel(Level.WARN);
		} else if ("ERROR".equalsIgnoreCase(logLevel)) {
			root.setLevel(Level.ERROR);
		} else if ("FATAL".equalsIgnoreCase(logLevel)) {
			root.setLevel(Level.FATAL);
		} else {
			exiteNivelLogger = false;
		}

	}

	public List<SelectItem> getLstLevel() {
		return lstLevel;
	}

	public void setLstLevel(List<SelectItem> lstLevel) {
		this.lstLevel = lstLevel;
	}

	public List<Log4jdata> getLstLogger() {
		return lstLogger;
	}

	public void setLstLogger(List<Log4jdata> lstLogger) {
		this.lstLogger = lstLogger;
	}

	public LoggerFiltroDTO getSlogfilter() {
		return slogfilter;
	}

	public void setSlogfilter(LoggerFiltroDTO slogfilter) {
		this.slogfilter = slogfilter;
	}

	public Integer getiCantLogger() {
		return iCantLogger;
	}

	public void setiCantLogger(Integer iCantLogger) {
		this.iCantLogger = iCantLogger;
	}

	public String getsPath() {
		return sPath;
	}

	public void setsPath(String sPath) {
		this.sPath = sPath;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public String getsValuePaquete() {
		return sValuePaquete;
	}

	public void setsValuePaquete(String sValuePaquete) {
		this.sValuePaquete = sValuePaquete;
	}

}
